speaker1 = 'speaker1.wav';
[s1,Fs1,b1] = wavread(speaker1);

%pre-Emphasis
a = 0.95;
pe_s1 = filter([1-a],1,s1);
time = (1:length(s1))/Fs1;
wavwrite(pe_s1,Fs1,b1,'preEmphasis_speaker1.wav');

%Framing
f_length = 20; %160 amostras por frame
o_length = 10; %overlap de 1/2

f_size = Fs1*f_length/1000;
o_size = f_size*o_length/f_length;

F = cell(145,1);
x = zeros(1,f_size);
y = zeros(1,f_size);
i=1;
k=1;
j=1;
frame_cut = f_size;

while i<length(pe_s1)
    %F{j} = x;
    x(k) = pe_s1(i);
    y(k) = pe_s1(i);
    x(k) = x(k) *(2^15);
    y(k) = y(k) *(2^15);
    k = k+1;
    i= i+1;
    if i==frame_cut
       F{j} = x;
       j = j+1;
       frame_cut = j*f_size - (j-1)*o_size;
       i = frame_cut - f_size;
       k=1;
       y = zeros(1,f_size);
    end        
end
F{j} = y;

H = cell(145,1);
x = zeros(1,160);
y = zeros(1,160);
i = 1;
w = zeros(1,160);
for j=1:145
    x = F{j};
    for i=1:160
        theta = (2*pi*(i-1))/(f_size - 1);
        w(i) = 0.56 - (0.46*cos(theta));
        y(i) = x(i) * w(i);
    end
    H{j} = y;
end

x = zeros(1,160);
hammed_s1 = zeros(23200,1);
k = 1;
while k < length(hammed_s1)
    for j=1:145
        x = H{j};
        for i=1:160
            hammed_s1(k) = x(i);
            k = k+1;
        end
        x = zeros(1,160);
    end
end

fft_length = 2^nextpow2(length(hammed_s1));
fft_s1 = fft(hammed_s1, length(hammed_s1));

M_mel = 23;        
K_mel = (length(fft_s1)/2) + 1;
R_mel = [300,3700];

hz2mel = @(hz)(1127*log(1+hz/700)); 
mel2hz = @(mel)(700*exp(mel/1127)-700);

[Mel_s1, freq_s1] = trifbank( M_mel, K_mel, R_mel, Fs1, hz2mel, mel2hz );

FBE_s1 = zeros(23,1);
lim = 1e-100;
for i=1:M_mel
    sum = 0;
    for j=1:K_mel
        sum = sum + ( (abs(fft_s1(j)^2)) * Mel_s1(i,j) );
    end
    if sum == 0
        sum = lim;
    end
    FBE_s1(i) = sum;
end

DCT_s1 = dct(FBE_s1,M_mel);

ceplifter = @( N, L )( 1+0.5*L*sin(pi*[0:N-1]/L) );

for i=1:M_mel
    CC_s1(i) = DCT_s1(i) * log(FBE_s1(i));
end

lifter = ceplifter(1,23);
CC_fs1 = CC_s1;
CC_fs1 = diag(lifter) * CC_fs1; % ~ HTK's MFCCs

%FBE_s1 = Mel_s1 * mag(1:K,:);